package com.afadev.wxgzh.controller;

import com.alibaba.fastjson.JSONObject;
import com.afadev.wxgzh.common.WxUrlConfig;
import com.afadev.wxgzh.common.WxAppConfig;
import com.afadev.wxgzh.common.WxConstant;
import com.afadev.wxgzh.domain.AccessToken;
import com.afadev.wxgzh.util.HttpUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author ：linzf
 * @description：微信扫码 控制器
 * @date ：2021/8/1 下午10:16
 */
@Log4j2
@Controller
public class WxSmController {
    private WxUrlConfig wxUrlConfig =new WxUrlConfig();

    @ResponseBody
    @GetMapping(value = "/wxLogin")
    public String getWechatQrCode() {
        try {
            return  wxUrlConfig.getWxWebLoginUrl(WxConstant.OAUTH_WEB_LOGIN, WxAppConfig.WX_BCALLBACK_URL, null, WxAppConfig.WX_APP_ID);
        } catch (Exception e) {
            return null;
        }
    }

    @ResponseBody
    @GetMapping(value = "/wxCallback")
    public void wxCallBack(HttpServletRequest request,HttpServletResponse response)  {
        String code = request.getParameter("code");
        try {
            String result = HttpUtil.doGet(wxUrlConfig.getOauthAccessToken(code, WxAppConfig.WX_APP_ID, WxAppConfig.WX_APP_SECRET));
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer errcode = jsonObject.getInteger("errcode");
            if (errcode != null) {
                log.info("微信回调失败，授权终止！");
                return;
            }
            AccessToken accessToken = JSONObject.toJavaObject(jsonObject, AccessToken.class);
            if (accessToken == null) {
               log.info("微信回调处理失败！获取accessToken时无返回结果！");
                return ;
            }

            JSONObject returnJson = getUserInfoByAccessToken(accessToken.getAccess_token(), accessToken.getOpenid());
           log.info("微信用户信息获取完毕*****************************************");
           log.info(returnJson.toJSONString());

            response.sendRedirect("http://127.0.0.1:8080/#/index?accessToken=123456&expiresIn=42100");
            //这里获取到用户信息 就打印出来了  其他你自己实现
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过accessToken获取用户信息
     */
    public JSONObject getUserInfoByAccessToken(String accessToken, String openId) {
       log.info("通过accessToken获取用户信息 参数：accessToken：" + accessToken + "*******参数openId：" + openId);
        JSONObject returnJson = new JSONObject();
        returnJson.put("code", 1);
        try {
            String result = HttpUtil.doGet(wxUrlConfig.getUserInfo(accessToken, openId));
            if (StringUtils.isBlank(result)) {
               log.info("通过授权accessToken获取用户信息失败！" + accessToken + "openId:" + openId);
                return null;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer errcode = jsonObject.getInteger("errcode");
            if (errcode != null) {
                if ("40001".equals(errcode)) {
                   log.info("授权过期，请重新授权！");
                } else {
                   log.info("获取用户信息失败！" + jsonObject.toJSONString());
                }
                return null;
            }
            returnJson.put("data", jsonObject);
            returnJson.put("code", 0);
            returnJson.put("msg", "获取微信用户信息成功");
        } catch (Exception e) {
            e.printStackTrace();
           log.info("通过accesstoken获取用户详细信息异常" + e.getMessage());
        }
        return returnJson;
    }

}
